/**
 * 
 */
package com.yunyike.wx.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Map;
import java.util.concurrent.ExecutionException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;

import com.yunyike.constants.CommonConstant;
import com.yunyike.utils.CookieUtils;
import com.yunyike.wx.common.Oauth;
import com.yunyike.wx.common.WeChat;
import com.yunyike.wx.common.WeiXinPropertiesUtil;

import net.sf.json.JSONObject;

/**
 * @author zhengqiang.shi
 * 2015年12月25日 下午12:08:53
 */
public class WeiXinUtil {

	private static final Logger log = LoggerFactory.getLogger(WeiXinUtil.class);
	
	public static void InitData(HttpServletRequest request, Model model) {
		String jsapiTicket = null;	// 微信的js sdk access ticket
		String url = null;	// 安全域名(用到sdk的页面)
		String timestamp = null;	// 时间戳
		String nonceStr = null;	// 随机字符串 （验证用）
		String signature = null;	// 签名
		try {
//			jsapiTicket = WeChat.getTicket().get("ticket").toString();
			jsapiTicket = WeChat.getTicket();
			model.addAttribute("errorMSG", "");
		} catch (KeyManagementException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			model.addAttribute("errorMSG", "");
		} catch (NoSuchAlgorithmException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			model.addAttribute("errorMSG", "");
		} catch (NoSuchProviderException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			model.addAttribute("errorMSG", "");
		} catch (InterruptedException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			model.addAttribute("errorMSG", "");
		} catch (ExecutionException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			model.addAttribute("errorMSG", "");
		} catch (IOException e) {
			log.error("打开扫一扫获取ticket错误:{}", e);
			model.addAttribute("errorMSG", "");
		}
		// 得到ticket
		url = request.getRequestURL().toString(); // 得到url
		log.info("获取本页面url为:{},ticket为:{}", url, jsapiTicket);
		// 得到包含url,jsapi_ticket,nonceStr,timestamp和signature的map
		Map<String, String> map = WeChat.jsApiSign(jsapiTicket, url);
		timestamp = map.get("timestamp");
		nonceStr = map.get("nonceStr");
		signature = map.get("signature");
		// 得到输入流中的AppId以供页面使用
		model.addAttribute("appId", WeiXinPropertiesUtil.getAppId());
		model.addAttribute("timestamp", timestamp);
		model.addAttribute("nonceStr", nonceStr);
		model.addAttribute("signature", signature);
		
		//String openId = getOpenId(request);
		
		
	}
	
	/**
	 * 从cookie 中获取用户的openId
	 */
	public static String getOpenId(HttpServletRequest request){
		
		// 先从cookie中获取 
		String cookieValue = CookieUtils.getCookieValue(request, CommonConstant.COOKIE_OPENID_KEY);
		if(StringUtils.isNotBlank(cookieValue)){
			return cookieValue;
			
		}
		
		// session中获取 
		HttpSession session = request.getSession();
		String openId = (String) session.getAttribute("myOpenid");
		
		if(StringUtils.isNotBlank(openId)){
			return openId;
		}
		
		return null;
	}
	
	public static void auth(HttpServletRequest request, HttpServletResponse response) throws Exception{
		
		// 微信用户授权接口所需
		String code = request.getParameter("code");
		
		// 没有code 去拿 code
		if(StringUtils.isBlank(code)){
			getCode(request, response);
		}else{
			// 有code 获取 token
			JSONObject jsonObject = JSONObject.fromObject(Oauth.getToken(code));
			String openid = jsonObject.getString("openid");
		}
		
	}
	
	public static void getCode(HttpServletRequest request, HttpServletResponse response) throws Exception{
		log.info("用户请求的 code 没值,表示需要授权");
		// 没有调用授权接口，那么就调用它
		// 获得现在的网址
		String currenturl = request.getRequestURL()
				+ (request.getQueryString() == null ? "" : ("?" + request.getQueryString()));
		// 构造授权接口地址
		String redirectUrl = Oauth.getCode(URLEncoder.encode(currenturl, "utf-8"), true);
		// 直接跳转到目标url
		ServletUtils.redirectToUrl(request, response, redirectUrl);
	}
}
